<template>
  <div>
    <h3 style="margin-bottom:20px">{{ id ? '编辑' : '新建' }}视频</h3>
    <el-form label-width="80px" :model="model" @submit.native.prevent="save">
      <el-form-item label="视频标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="视频播放">
        <el-input v-model="model.playNum"></el-input>
      </el-form-item>
      <el-form-item label="视频弹幕">
        <el-input v-model="model.danmu"></el-input>
      </el-form-item>
      <el-form-item label="视频分类">
        <template>
          <el-select v-model="model.category" clearable placeholder="请选择">
            <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item._id">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="视频图片">
        <el-upload class="avatar-uploader" :action="$http.defaults.baseURL + '/upload'" :show-file-list="false"
          :on-success="res => $set(model, 'img', res.url)">
          <img v-if="model.img" :src="model.img" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">{{
          id ? '保存变更' : '立即创建'
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['id'],
  data () {
    return {
      model: {},
      options: []
    }
  },
  methods: {
    async save () {
      if (this.id) {
        await this.$http.put(`/common/video/${this.id}`, this.model)
      } else {
        await this.$http.post('/common/video', this.model)
      }
      this.$router.push('/video/list')
      this.$message({
        type: 'success',
        message: '创建成功'
      })
    },
    async fetchVideo () {
      const res = await this.$http.get(`/common/video/${this.id}`)
      this.model = res.data
    },
    async fetchCategory () {
      const res = await this.$http.get('/common/category')
      console.log(res)
      this.options = res.data
    }
  },
  created () {
    this.id && this.fetchVideo()
    this.fetchCategory()
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  min-width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px !important;
}
.avatar {
  min-width: 178px;
  height: 178px;
  display: block;
}
</style>
